package com.glory.dgcpcpda.activity.mfg;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.FTSampleListAdapter;
import com.glory.dgcpcpda.adapter.SampleListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.MyApp;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.SimpleEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.entity.response.ResponseHeader;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * FileName: FTTrackOutBiandaiActivity
 * Author: XJH
 * Date: 2020/5/22 9:08
 * Description:编带出站FT测试
 * 点击提交按钮，请求接口，根据接口返回信息跳转正常出站、异常出站界面，正常出站成功后，跳转清料页面
 * History:
 */
public class FTTrackOutBiandaiActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvErrorOut)
    TextView tvErrorOut;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.tvLotNum)
    TextView tvLotNum;
    @BindView(R.id.tvHoldState)
    TextView tvHoldState;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvSampleList)
    RecyclerView rvSampleList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private FTSampleListAdapter mSampleListAdapter;
    private String mEqpID = "";
    private String mPackageType = "";
    private transient FreeUI_GeneralFragmentDialog tipDialog;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_track_out_biandai_ft;
    }

    @Override
    protected void initView() {
        initLayout();
    }

    private void initLayout() {
        listTv1.setText("BIN名称");
        listTv2.setText("BIN描述");
        listTv3.setText("数量");
        listTv4.setText("占比良率");
        tvTitle.setText("出站(FT测试-向导)");
        setMainLayout(llMain);
        tvBaseSubmit.setText("下一步");
        initRecyclerView(rvSampleList,this);
        mSampleListAdapter = new FTSampleListAdapter(null,false);
        mSampleListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mSampleListAdapter.isFirstOnly(true);
        rvSampleList.setAdapter(mSampleListAdapter);
        addActivity(this);


        initEdit(etLot, s -> LotUtils.searchLotInfo(FTTrackOutBiandaiActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                mEqpID = response.getLOT().getEQUIPMENTID();
                tvLotNum.setText(response.getLOT().getMAINQTY());
                tvHoldState.setText(response.getLOT().getHOLDSTATE());
                mPackageType = response.getLOT().getMAINMATTYPE();
                mSampleListAdapter.setMainQTY(Integer.parseInt(response.getLOT().getMAINQTY()));
                requestBinInfo(s,"SelectBinData");
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t,"LOTQUERY");
            }
        }));
    }

    private void requestBinInfo(String lotID,String actionType) {
        FreeUI_EntityCallBack<BaseResponseBean<SimpleEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<SimpleEntity>>
                (new TypeToken<BaseResponseBean<SimpleEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onSuccess(response);
                ResponseHeader header = response.body().getResponse().getHeader();

                if (header.getRESULT().toUpperCase().equals("SUCCESS")) {
                    SimpleEntity entity = response.body().getResponse().getBody();
                    if (!entity.getTRACKSHOWMSG().equals("")){
                        FreeApi_DialogUtils.getConfirmDialog(FTTrackOutBiandaiActivity.this, "确定", entity.getTRACKSHOWMSG(), () -> {
                            if (actionType.equals("SelectBinData")){
                                if (entity.getLOTBINDATALIST().size() <= 0){
                                    showToast("暂无BIN测试数据",false);
                                    tvErrorOut.setVisibility(View.VISIBLE);
                                    return;
                                }
                                tvErrorOut.setVisibility(View.GONE);
                                List<SimpleEntity.MantissaLotBinData> list = new ArrayList<>();
                                Map<String,SimpleEntity.MantissaLotBinData> map = new HashMap<>();
                                for (int i = 0; i < entity.getLOTBINDATALIST().size(); i++) {
                                    if (map.containsKey(entity.getLOTBINDATALIST().get(i).getBINNAME())){
                                        SimpleEntity.MantissaLotBinData mantissaLotBinData1 = entity.getLOTBINDATALIST().get(i);
                                        SimpleEntity.MantissaLotBinData mantissaLotBinData = map.get(entity.getLOTBINDATALIST().get(i).getBINNAME());
                                        mantissaLotBinData.setMAINQTY(mantissaLotBinData.getMAINQTY() + mantissaLotBinData1.getMAINQTY());
                                        map.put(entity.getLOTBINDATALIST().get(i).getBINNAME(),mantissaLotBinData);
                                    }else {
                                        map.put(entity.getLOTBINDATALIST().get(i).getBINNAME(),entity.getLOTBINDATALIST().get(i));
                                    }
                                }

                                ArrayList<Double> strings = new ArrayList<>();

                                for(Map.Entry<String, SimpleEntity.MantissaLotBinData> entry : map.entrySet()){
                                    String[] ns = entry.getValue().getBINNAME().split("N");
                                    String binName = "";
                                    if (ns[1].contains("_")){
                                        binName = ns[1].replace("_",".");
                                    }else{
                                        binName = ns[1];
                                    }
                                    strings.add(Double.parseDouble(binName));
                                    entry.getValue().setCODE(Double.parseDouble(binName));
                                    list.add(entry.getValue());
                                }
                                Collections.sort(strings);
                                List<SimpleEntity.MantissaLotBinData> simpleEntityList = new ArrayList<>();
                                for (Double s:strings) {
                                    for (SimpleEntity.MantissaLotBinData sm:list) {
                                        if (s == sm.getCODE()){
                                            simpleEntityList.add(sm);
                                        }
                                    }
                                }

                                mSampleListAdapter.setNewData(simpleEntityList);
                            }else {
                                Bundle bundle = new Bundle();
                                bundle.putString("LOTID",getText(etLot));
                                bundle.putString("EQPID",mEqpID);
                                bundle.putString("LOTNUM",tvLotNum.getText().toString());
                                bundle.putString("PACKAGETYPE",mPackageType);
                                FreeApi_Utils.skipWithExtraIntent("", bundle,FTTrackOutBiandaiActivity.this, entity.getGUIDE().equals("FAIL")?
                                        FTTrackOutBiandaiErrorActivity.class : FTTrackOutBiandaiSuccessActivity.class);
//                        finish();
                            }
                            return;
                        }).show(getSupportFragmentManager(),"CONFIRM_DIALOG");
                    }else {
                        if (actionType.equals("SelectBinData")){
                            if (entity.getLOTBINDATALIST().size() <= 0){
                                showToast("暂无BIN测试数据",false);
                                tvErrorOut.setVisibility(View.VISIBLE);
                                return;
                            }
                            tvErrorOut.setVisibility(View.GONE);
                            List<SimpleEntity.MantissaLotBinData> list = new ArrayList<>();
                            Map<String,SimpleEntity.MantissaLotBinData> map = new HashMap<>();
                            for (int i = 0; i < entity.getLOTBINDATALIST().size(); i++) {
                                if (map.containsKey(entity.getLOTBINDATALIST().get(i).getBINNAME())){
                                    SimpleEntity.MantissaLotBinData mantissaLotBinData1 = entity.getLOTBINDATALIST().get(i);
                                    SimpleEntity.MantissaLotBinData mantissaLotBinData = map.get(entity.getLOTBINDATALIST().get(i).getBINNAME());
                                    mantissaLotBinData.setMAINQTY(mantissaLotBinData.getMAINQTY() + mantissaLotBinData1.getMAINQTY());
                                    map.put(entity.getLOTBINDATALIST().get(i).getBINNAME(),mantissaLotBinData);
                                }else {
                                    map.put(entity.getLOTBINDATALIST().get(i).getBINNAME(),entity.getLOTBINDATALIST().get(i));
                                }
                            }

                            ArrayList<Double> strings = new ArrayList<>();

                            for(Map.Entry<String, SimpleEntity.MantissaLotBinData> entry : map.entrySet()){
                                String[] ns = entry.getValue().getBINNAME().split("N");
                                String binName = "";
                                if (ns[1].contains("_")){
                                    binName = ns[1].replace("_",".");
                                }else{
                                    binName = ns[1];
                                }
                                strings.add(Double.parseDouble(binName));
                                entry.getValue().setCODE(Double.parseDouble(binName));
                                list.add(entry.getValue());
                            }
                            Collections.sort(strings);
                            List<SimpleEntity.MantissaLotBinData> simpleEntityList = new ArrayList<>();
                            for (Double s:strings) {
                                for (SimpleEntity.MantissaLotBinData sm:list) {
                                    if (s == sm.getCODE()){
                                        simpleEntityList.add(sm);
                                    }
                                }
                            }

                            mSampleListAdapter.setNewData(simpleEntityList);
                        } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("LOTID",getText(etLot));
                        bundle.putString("EQPID",mEqpID);
                        bundle.putString("LOTNUM",tvLotNum.getText().toString());
                        bundle.putString("PACKAGETYPE",mPackageType);
                        FreeApi_Utils.skipWithExtraIntent("", bundle,FTTrackOutBiandaiActivity.this, entity.getGUIDE().equals("FAIL")?
                                FTTrackOutBiandaiErrorActivity.class : FTTrackOutBiandaiSuccessActivity.class);
//                        finish();
                        }
                    }

                }else {
                    tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, "确定", BaseResponseBean.getMessage(header), () -> {
                        String resultmessage = response.body().getResponse().getHeader().getRESULTMESSAGE();
                        if ("wip.workorder_not_sampled_please_sample_trackout".equals(resultmessage)){
                            Bundle bundle = new Bundle();
                            bundle.putString("LOTID",getText(etLot));
                            FreeApi_Utils.skipWithExtraIntent("", bundle,FTTrackOutBiandaiActivity.this, FTSampleTrackOutActivity.class);
                        }
                    });
                    tipDialog.show(getSupportFragmentManager(),"DIALOG");

                }


            }

            @Override
            public void onError(Response<BaseResponseBean<SimpleEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTFTTRACKOUT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", actionType);
        map.addProperty("EQUIPMENTID", etEqpWorkID.getText().toString());
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(lotID));
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());
        if (mSampleListAdapter.getSelectorData() != -1){
            ArrayList<SimpleEntity.MantissaLotBinData> mantissaLotBinData = new ArrayList<>();
            mantissaLotBinData.add(mSampleListAdapter.getData().get(mSampleListAdapter.getSelectorData()));
            map.add("LOTBINDATALIST", new JsonParser().parse(new Gson().toJson(mantissaLotBinData)).getAsJsonArray());
        }
        NetUtils.requestPostNet("CPC.LOTFTTRACKOUT", "LOTFTTRACKOUT", this, map, callBack);
    }

    @Override
    protected void initData() {}

    @OnClick({R.id.tvBaseSubmit,R.id.tvErrorOut})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvBaseSubmit:
                if (actionControl("Submit07"))return;
                if (getText(etLot).equals("")){
                    showToast("请先扫描批次号",false);
                    return;
                }
                if (!getText(etEqpWorkID).equals(mEqpID)){
                    etEqpWorkID.setText("");
                    etEqpWorkID.requestFocus();
                    showToast("当前批次不在此设备上，请重新扫描设备!",false);
                    return;
                }
                showSubmitDialog(() -> requestBinInfo(getText(etLot),"GuideTrackout"),"是否进行下一步");
                break;
            case R.id.tvErrorOut:
                Bundle bundle = new Bundle();
                bundle.putString("LOTID",getText(etLot));
                bundle.putString("EQPID",mEqpID);
                bundle.putString("LOTNUM",tvLotNum.getText().toString());
                bundle.putString("PACKAGETYPE",mPackageType);
                bundle.putString("ISERROROUT","true");
                FreeApi_Utils.skipWithExtraIntent("", bundle,
                        FTTrackOutBiandaiActivity.this,
                        FTTrackOutBiandaiErrorActivity.class);
                break;
        }
        }


}
